<template>
  <div class="app-container">
    <div style="display: grid;grid-template-rows: auto minmax(0, 6fr) minmax(0, 4fr); grid-template-columns: minmax(0, 1fr); height: 100%;grid-gap: 15px;">
      <div class="top-title">
        <div></div>
        <h1 style="text-align: center;margin: 0">{{companyShortName}}注塑机生产看板</h1>
        <div style="display: flex;justify-content: flex-end;font-size: 14px;line-height: 0;">
          <div style="padding: 0 10px;">
<!--            欢迎您，<svg-icon icon-class="user"></svg-icon> {{userName}}，-->
            <el-button @click="logout" type="text" size="small" style="color: #428dd5;"><svg-icon icon-class="logout"></svg-icon> 退出登录</el-button>
          </div>
        </div>
      </div>
      <div class="content" style="height: 100%;">
        <div style="height: 100%;display: grid;grid-template-columns: auto minmax(0, 6fr) minmax(0, 4fr);grid-template-rows: minmax(0, 1fr);grid-gap: 15px;">
          <div class="left-menu" style="width: 200px;height: 100%;display: grid;grid-template-rows: minmax(0, 1fr) auto;overflow-y: auto">
            <div>
              <div style="height: 100%;overflow: auto">
                <el-menu
                  active-text-color="#409eff"
                  background-color="rgba(0, 0, 0, 0)"
                  text-color="rgba(255, 255, 255, 0.8)"
                  style="border-right: none;height: 100%;overflow: auto"
                  @select="changeDevice"
                >
                  <el-menu-item :index="'_'">
                    <popper trigger="hover" :append-to-body="true" :options="{ placement: 'right', appendToBody: true }">
                      <div>
                        <el-menu>
                          <el-menu-item @click="$router.push('/plastic-data')" style="color: #2ac06d;">详细数据</el-menu-item>
                        </el-menu>
                      </div>
                      <div slot="reference">
                        <span class="device-name" @click="deviceList.forEach(d => d.showPopover = false);">
                          <svg-icon icon-class="list" />
                          <span>全部</span>
                          <el-tag>运行：{{ (deviceList || []).filter(d => d.online === 1 && d.runState === 1).length }}</el-tag>
                        </span>
                      </div>
                    </popper>
                  </el-menu-item>
                  <el-menu-item v-for="(device, index) in (deviceList || [])" :key="device.deviceId" :index="device.deviceId + ''" style="margin-left: 10px">
                    <popper trigger="hover" :append-to-body="true" :options="{ placement: 'right', appendToBody: true }">
                      <div>
                        <el-menu>
                          <el-menu-item @click="$router.push('/plastic-data?deviceId=' + device.deviceId)" style="color: #2ac06d;">详细数据</el-menu-item>
                          <el-menu-item @click="editDeviceData = {...device}; editDeviceVisible = true" style="color: #409eff;">修改</el-menu-item>
                          <el-menu-item @click="removeDevice(device)" style="color: #F6416C;">删除</el-menu-item>
                        </el-menu>
                      </div>
                      <div slot="reference">
                        <span class="device-name">
                          <svg-icon icon-class="component" />
                          <span>{{ device.deviceName }}</span>
                          <el-tag v-if="device.runState === -1" type="danger">停机</el-tag>
                          <el-tag v-else-if="device.runState === 2" type="danger">告警</el-tag>
                          <el-tag v-else-if="device.runState === 0" type="warning">待机</el-tag>
                          <el-tag v-else type="success">运行</el-tag>
                        </span>
                      </div>
                    </popper>
                  </el-menu-item>
                </el-menu>
              </div>
            </div>

            <el-button style="margin: 10px auto 0 auto;width: 80%;" @click="editDeviceVisible=true">添加设备</el-button>
          </div>
          <div>
            <line-chart :device-id="selectDeviceId" />
          </div>
          <div style="display: grid;grid-template-rows: minmax(0, 1fr) minmax(0, 1fr);;grid-gap: 15px;">
            <div style="display: grid;grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);grid-gap: 10px;">
              <div>
                <pie-chart :devices="deviceList" :device-id="selectDeviceId" />
              </div>
              <div>
                <bar-chart />
              </div>
            </div>
            <div>
              <device-state-table :device-id="selectDeviceId" />
            </div>
          </div>
        </div>
      </div>
      <div>
        <data-log-table :device-id="selectDeviceId" />
      </div>
    </div>

    <el-dialog :visible="editDeviceVisible" :title="`${editDeviceData.deviceId == null ? '添加' : '修改'}设备`" :close-on-click-modal="false" @close="editDeviceVisible = false">
      <el-form label-width="120px">
        <el-form-item label="设备名称">
          <el-input v-model="editDeviceData.deviceName" />
        </el-form-item>
        <el-form-item label="设备序列号">
          <el-input v-model="editDeviceData.deviceNo" :disabled="editDeviceData.deviceId != null" />
        </el-form-item>
        <el-form-item label="模穴数">
          <el-input v-model="editDeviceData.deviceHoleCount" type="number" />
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="saveDeviceInfo">{{ editDeviceData.deviceId == null ? '添加' : '修改' }}设备</el-button>
          <el-button @click="editDeviceVisible = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import 'vue-popperjs/dist/vue-popper.css'
import httpRequest from '@/utils/request'
import LineChart from '@/views/plastic/LineChart'
import BarChart from '@/views/plastic/BarChart'
import PieChart from '@/views/plastic/PieChart'
import DataLogTable from '@/views/plastic/DataLogTable'
import DeviceStateTable from '@/views/plastic/DeviceStateTable'
import Popper from 'vue-popperjs'
import vueStateMixin from "@/utils/vue-state-mixin"
import {ElMessage, ElMessageBox} from "element-ui"
import request from "@/utils/request";

export default {
  name: 'PlasticIndex',
  mixins: [vueStateMixin],
  components: { DeviceStateTable, DataLogTable, PieChart, BarChart, LineChart, Popper },
  computed: {
    userName() {
      let userInfo = this.$store.getters.userInfo;
      if(userInfo != null) {
        return userInfo.userName;
      }
      return null;
    },
    companyShortName() {
      let userInfo = this.$store.getters.userInfo;
      if(userInfo != null) {
        return userInfo.companyShortName;
      }
      return null;
    }
  },
  data() {
    return {
      t: false,
      selectDeviceId: null,
      deviceList: null,
      editDeviceVisible: false,
      editDeviceData: {
        deviceId: null,
        deviceName: null,
        deviceNo: null,
        deviceHoleCount: 1
      }
    }
  },
  watch: {
    editDeviceVisible() {
      if (!this.editDeviceVisible) {
        this.editDeviceData.deviceId = null
        this.editDeviceData.deviceName = null
        this.editDeviceData.deviceNo = null
        this.editDeviceData.deviceHoleCount = 1
      }
    }
  },
  created() {
    this.loadDeviceList()

    setInterval(() => {
      if(this.pageActivate) {
        this.loadDeviceList()
      }
    }, 10 * 1000)
  },
  methods: {
    changeDevice(index, indexPath, item, routeResult) {
      if (index === '_') {
        this.selectDeviceId = null
      } else {
        this.selectDeviceId = parseInt(index)
      }
    },
    loadDeviceList() {
      httpRequest({
        url: '/api/device/loadAllDevice'
      }).then(resp => {
        if (resp.success) {
          this.deviceList = resp.data
        } else {
          this.$message.error(resp.message)
        }
      })
    },
    saveDeviceInfo() {
      if (this.editDeviceData.deviceName == null || this.editDeviceData.deviceName == '') {
        this.$message.error('请输入设备名称')
        return
      }
      if (this.editDeviceData.deviceNo == null || this.editDeviceData.deviceNo == '') {
        this.$message.error('请输入设备序列号')
        return
      }
      if (this.editDeviceData.deviceHoleCount == null || this.editDeviceData.deviceHoleCount == '' || Number.isNaN(this.editDeviceData.deviceHoleCount)) {
        this.$message.error('请输入设备模穴数')
        return
      }

      httpRequest({
        url: '/api/device/edit',
        method: 'post',
        data: this.editDeviceData
      }).then(resp => {
        if (resp.success) {
          this.loadDeviceList()
          this.editDeviceVisible = false
        } else {
          this.$message.error(resp.message)
        }
      })
    },
    removeDevice(deviceInfo) {
      this.$msgbox({
        title: "确定要删除此设备吗？",
        message: `确定要删除“${deviceInfo.deviceName}”吗？`,
        confirmButtonText: "确定删除",
        showCancelButton: true,
        cancelButtonText: "取消"
      }).then(() => {
        request({
          url: "/api/device/removeDevice",
          method: "post",
          data: {
            deviceId: deviceInfo.deviceId
          }
        }).then(resp => {
          if(resp.success) {
            this.loadDeviceList();
            this.$message.success("删除成功")
          } else {
            this.$message.error(resp.message)
          }
        });
      });
    },
    logout() {
      this.$store.dispatch("user/logout").finally(() => {
        this.$router.replace("/login")
      })
    },
  }
}
</script>

<style scoped lang="scss">
  .app-container {
    height: 100%;
    padding: 0;
    color: #ffffff;
    background-color: #000228;

    .top-title {
      background-image: url("~@/assets/35.bg.jpg");
      background-size: 100% 100%;
      line-height: 80px;
      height: max-content;
      display: grid;
      grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);

      h1 {
        padding: 0;
        margin: 0;
        font-size: 24px;
        padding: 8px 0;
      }
    }

    .left-menu {
      .device-name {
        height: 100%;
        display: grid;
        grid-gap: 5px;
        align-items: center;
        grid-template-columns: auto minmax(0, 1fr) auto;

        span {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
</style>
<style>
[x-placement] {
  left: 200px !important;
}
</style>
